package command

import (
	"backend/internal/models"
	"backend/pkg/utils"

	"github.com/spf13/cobra"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type MigrateHandler struct {
	logger *zap.Logger
	db     *gorm.DB
}

func NewMigrateHandler(logger *zap.Logger, db *gorm.DB) *MigrateHandler {
	return &MigrateHandler{
		logger: logger,
		db:     db,
	}
}

func (h *MigrateHandler) Migrate(cmd *cobra.Command, args []string) {
	err := h.db.AutoMigrate(
		&models.User{},
		&models.Media{},
	)

	if err != nil {
		cmd.Println("database migrate error:", err)
		return
	}

	// 初始化admin用户（如果不存在）
	var adminCount int64
	err = h.db.Model(&models.User{}).Where("user_name = ?", "admin").Count(&adminCount).Error
	if err != nil {
		cmd.Println("check admin user error:", err)
		return
	}

	// 如果不存在admin用户，则创建
	if adminCount == 0 {
		// 使用bcrypt加密默认密码
		hashedPassword := utils.BcryptMake([]byte("admin123"))
		
		adminUser := models.User{
			UserName: "admin",
			Password: hashedPassword,
		}
		
		err = h.db.Create(&adminUser).Error
		if err != nil {
			cmd.Println("create admin user error:", err)
		} else {
			cmd.Println("admin user created successfully, username: admin, password: admin123")
		}
	} else {
		cmd.Println("admin user already exists, skip initialization")
	}

	cmd.Println("database migrate success")
}
